package kin.system.util;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;



import org.springframework.stereotype.Controller;

public class ScanClassesOfPackage {
	
	
	
	

	public  static Class<?>[] getClasses(String packageName,Class filterClass)
			throws ClassNotFoundException, IOException {

		String path = packageName.replace('.', '/');
		Enumeration<URL> resources = Thread.currentThread()
				.getContextClassLoader().getResources(path);
		List<File> dirs = new ArrayList<File>();

		while (resources.hasMoreElements()) {
			URL resource = resources.nextElement();
			dirs.add(new File(resource.getFile()));
		}
		ArrayList<Class> classes = new ArrayList<Class>();
		for (File directory : dirs) {
			classes.addAll(findClasses(directory, packageName,filterClass));
		}
		return classes.toArray(new Class[classes.size()]);
	}

	private static List<Class> findClasses(File directory, String packageName,Class filterClass)
			throws ClassNotFoundException {
		List<Class> classes = new ArrayList<Class>();

		if (!directory.exists()) {
			return classes;
		}
		File[] files = directory.listFiles();
		for (File file : files) {
			//System.out.println(packageName + "." + file.getName());
			if (file.isDirectory()) {
				classes.addAll(findClasses(file,
						packageName + "." + file.getName(),filterClass));
			} else if (file.getName().endsWith(".class")
					&& Class.forName(
							packageName + "."
									+ file.getName().replace(".class", ""))
							.getAnnotation(filterClass) != null) {
				classes.add(Class.forName(packageName
						+ '.'
						+ file.getName().substring(0,
								file.getName().length() - 6)));
			}
		}
		return classes;
	}
	

	

	


	
	
	
	 public static void main(String[] args) throws Exception { Class[] clas =
			 ScanClassesOfPackage.getClasses("kin.controller",Controller.class); for (Class cla : clas) {
	 System.out.println(cla.getName()); } }
	 
}
